package com.frejoys.task;

import cn.hutool.core.util.RandomUtil;
import com.frejoys.common.enums.EStoreActivityQueueStatus;
import com.frejoys.common.enums.EStoreActivityType;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.dao.entity.StoreActivity;
import com.frejoys.dao.entity.StoreActivityQueue;
import com.frejoys.dao.mapper.GoodsMapper;
import com.frejoys.service.GoodsService;
import com.frejoys.service.RebateService;
import com.frejoys.service.StoreActivityQueueService;
import com.frejoys.service.StoreActivityService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

// 商品售出数量变量任务
@Component
@RequiredArgsConstructor
public class GoodsVarSoldCountTask {

    // @Scheduled(cron = "{秒数} {分钟} {小时} {日期} {月份} {星期}")

    private final RedissonClient redissonClient;

    private final GoodsService goodsService;

    private final GoodsMapper goodsMapper;

    /**
     * 每20分钟，更新售出数量变量
     */
    // @Async
    // @Scheduled(cron = "0 */2 * * * ?")
    // @Scheduled(cron = "0 */60 8-22 * * ?")
    public void dispatchGoodsVarSoldCountQueue() {

        RLock lock = redissonClient.getLock(CacheKeyUtil.taskGoodsVarSoldCountLockKey());

        if (lock.tryLock()) {
            try {

                Integer page = 1;
                Integer size = 1000;

                while (true) {

                    // 获取商品id
                    List<Integer> ids = goodsService.getGoodsIdList(page, size);
                    if (ids.isEmpty()) {
                        break;
                    }

                    for (Integer id : ids) {
                        int rInt = RandomUtil.randomInt(0, 5);

                        // int rInt = 0;

                        // int typeInt = RandomUtil.randomInt(0, 3);
                        //
                        // if (typeInt == 0) {
                        //     rInt = RandomUtil.randomInt(0, 5);
                        // } else if (typeInt == 1) {
                        //     rInt = RandomUtil.randomInt(0, 10);
                        // } else if (typeInt == 2) {
                        //     rInt = RandomUtil.randomInt(0, 15);
                        // } else if (typeInt == 3) {
                        //     rInt = RandomUtil.randomInt(0, 20);
                        // }

                        if (rInt > 0) {
                            goodsMapper.incrVarSoldCount(id, rInt);
                        }
                    }

                    page++;
                }

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }

    }











}
